import Vue from 'vue'
import co from 'co'
// import CommonService from './CommonService'
import * as Util from '../components/Util'

// 新开户
let initCardGen = function * (model, row) {
  try {
    // 写卡之前是否需要读一次卡或和卡服务及读卡器交互一次，以确保卡与卡服务相关系统正常，提高写卡成功率
    // let logicRes = yield Vue.$post(logicPath, {data: logicParams}, {resolveMsg: null, rejectMsg: '开户逻辑错误'})

    // 根据预购水量计算应交金额
    // let cal = yield CommonService.waterCalculate(data, data.f_payment)

    // 卡操作顺序：1.存库，2.后写卡，3.判断写卡是否成功，成功，修改售水标识，失败，业务回滚
    // 存库
    let result = yield co(saleWaterGen(model, row))
    Vue.console.info(result, 'CardService')
    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(result.data.cardnumber))
    // 写卡
    let params = {
      factory: row.f_alias,
      kmm: '000000',                                       // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
      kzt: '0',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
      kh: result.data.cardnumber,                          // 卡号
      yhh: row.f_meterid,                                  // 用户号，档案中自己输
      ql: model.f_prewater,                                  // 预购水量
      csql: '0',                                           // 上次购水量，新开户为0
      ccsql: '0',                                          // 上上次购水量，新开户为0
      cs: '1',                                             // 求购水次数，先开户为1
      ljgql: model.f_prewater,                               // 当前累计购水量
      bkcs: '0',                                           // 新开户卡，为0
      ljyql: '0',                                          // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      bjql: row.f_police_water,                              // 报警水量,t_waterbrand表中
      czsx: row.f_topup_ceil,                              // 充值上线，t_waterbrand表中
      tzed: row.f_overdr_lines,                            // 透支额度，t_waterbrand表中
      cssqrq: '',                                          // 上次售水日期，格式为YYYYMMDD
      sxrq: model.f_startdate,                             // 生效日期，价格管理中取
      meterid: row.f_meternumber,                          // 表号
      money: model.f_preamount,                            // 购水金额
      totalmoney: cardParams.data.f_collection,            // 累计金额
      // dqdm: '610113'                                       // 地区代码
    }

    let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '开户卡服务错误'}))
    // let cardRes = {
    //   data: {
    //     Err: null,
    //     Exception: null
    //   }
    // }
    // 卡服务写卡异常，业务逻辑回滚
    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      row.version = row.version + 1
      row.userinfo_version = row.userinfo_version + 1
      Vue.console.info(result.data.id, 'CardService')
      yield Vue.resetpost('rs/logic/salecardrollback', {data: {id: result.data.id, row: row}}, {resolveMsg: '开户失败', rejectMsg: '开户失败'})
    } else {
      // 如果成功修改标识(更新状态为有效)，将返回的卡密码写回数据库
      row.version = row.version + 1
      let data = {
        userfiles: {
          f_user_id: row.f_user_id,
          f_times: row.f_times + 1,
          version: row.version,
          f_card_id: result.data.cardnumber,
          f_card_password: cardRes.data.Kmm
        },
        record: {
          id: result.data.id,
          f_state: '有效'
        }
      }
      return yield Vue.resetpost('rs/logic/updatemark', {data: data}, {resolveMsg: '开户成功', rejectMsg: '开户修改状态失败'})
    }
  } catch (error) {
    Vue.console.error('出错', error)
  }
}

// 补卡管理
let replaceCardGen = function * (model, row) {
  try {
    // 存库
    let result = yield co(reissueCardGen(model, row))

    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(row.f_card_id))

    // 写卡
    let params = {
      factory: row.f_alias,
      kh: row.f_card_id,                                   // 卡号
      //kmm: row.f_card_password,                          // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
      bjql: row.f_police_water,                            // 报警水量,t_waterbrand表中
      czsx: row.f_topup_ceil,                              // 充值上线，t_waterbrand表中
      tzed: row.f_overdr_lines,                            // 透支额度，t_waterbrand表中
      kzt: '1',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
      ql: cardParams.data.f_prewater,                      // 购水量
      bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
      csql: cardParams.data.sc,                            // 上次购水量，新开户为0
      ccsql: cardParams.data.ssc,                          // 上上次购水量，新开户为0
      cs: row.times,                                       // 求购水次数，先开户为1
      ljgql: cardParams.data.f_prewater,                   // 当前累计购水量
      ljyql: cardParams.data.f_prewaterall,                // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      sxrq: model.f_startdate,                             // 生效日期，价格管理中取
      meterid: cardParams.data.f_meterid,                  // 表号
      money: model.f_preamount,                            // 购水金额
      totalmoney: cardParams.data.f_collection,            // 累计金额
      // dqdm: '610113'                                       // 地区代码
    }

    let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteNewCard', params, {resolveMsg: null, rejectMsg: '补卡卡服务错误'}))
    // let cardRes = {
    //   data: {
    //     Err: null,
    //     Exception: null
    //   }
    // }
    // 卡服务写卡异常，业务逻辑回滚
    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      yield Vue.resetpost('rs/logic/repairCardRoolBack', {data: {id: result.data.id}}, {resolveMsg: '补卡失败', rejectMsg: '补卡失败'})
    } else {
      // 如果成功修改标识(更新状态为有效)
      let data = {
        userfiles: {
          f_user_id: row.f_user_id,
          f_times: row.f_times + 1,
          version: row.version
        },
        record: {
          id: result.data.id,
          f_state: '有效'
        }
      }
      return yield Vue.resetpost('rs/logic/updatemark', {data: data}, {resolveMsg: '补卡成功', rejectMsg: '补卡修改状态失败'})
    }
  } catch (error) {
    Vue.console.error('出错', error)
  }
}

// 卡表收费
let sellWaterGen = function * (model, row) {
  try {
    // 存库
    let result = yield co(cardChargeGen(model, row))

    // 获取水价和售水情况参数
    let cardParams = yield co(getParamGen(row.f_card_id))
    // 写卡
    let params = {
      factory: row.f_alias,                                // 水表厂家
      kh: row.f_card_id,                                   // 卡号
      //kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
      bjql: row.f_police_water,                            // 报警水量,t_waterbrand表中
      czsx: row.f_topup_ceil,                              // 充值上线，t_waterbrand表中
      tzed: row.f_overdr_lines,                            // 透支额度，t_waterbrand表中
      bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
      ql: model.f_prewater,                                // 预购水量
      csql: cardParams.data.sc,                            // 上次购水量，新开户为0
      ccsql: cardParams.data.ssc,                          // 上上次购水量，新开户为0
      cs: row.f_times + 1,                                 // 求购水次数，先开户为1
      ljgql: cardParams.data.f_prewater,                   // 当前累计购水量
      ljyql: cardParams.data.f_prewaterall,                // 累积用水量，有些表要累加原来用水量,新开户卡，为0
      money: model.f_preamount,                            // 购水金额
      totalmoney: model.f_preamount                         // 累计金额
    }

    let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteGasCard', params, {resolveMsg: null, rejectMsg: '卡表收费卡服务错误'}))
    // let cardRes = {
    //   data: {
    //     Err: null,
    //     Exception: null
    //   }
    // }
    // 卡服务写卡异常，业务逻辑回滚
    if (!result || !cardParams || !cardRes || cardRes.data.Err || cardRes.data.Exception) {
      let data = {
        id: result.data.id,
        userinfo: {
          f_userinfo_id: row.f_userinfo_id,
          version: row.userinfo_version + 1,
          f_balance: row.f_balance
        }
      }
      yield Vue.resetpost('rs/logic/cardChargeRollback', {data: data}, {resolveMsg: '卡表收费失败', rejectMsg: '卡表收费失败'})
    } else {
      // 如果成功修改标识(更新状态为有效)
      let data = {
        userfiles: {
          f_user_id: row.f_user_id,
          f_times: row.f_times + 1,
          version: row.version
        },
        record: {
          id: result.data.id,
          f_state: '有效'
        }
      }
      return yield Vue.resetpost('rs/logic/updatemark', data, {resolveMsg: '售水成功', rejectMsg: '卡表收费修改状态失败'})
    }
  } catch (error) {
    Vue.console.error('出错', error)
  }
}

let reissueCardGen = function * (model, row) {
  if (model.f_fillcard_type === 'IC卡信息错乱') {
    model.f_reason = 'IC卡信息错乱'
  } else if (model.f_fillcard_type === 'IC卡丢失') {
    model.f_reason = 'IC卡丢失'
  } else if (model.f_fillcard_type === 'IC卡坏') {
    model.f_reason = 'IC卡坏'
  }
  if (model.f_cardfees === '') {
    model.f_cardfees = 0
  }
  let data = {
    f_user_id: row.f_user_id,
    f_fillcard_type: model.f_fillcard_type,
    f_fillcard_state: '有效',
    f_card_id: row.f_card_id,
    f_cardfees: model.f_cardfees,
    f_reason: model.f_reason,
    record_userinfo: row.f_userinfo_id,
    f_userinfo_id: row.f_userinfo_id,
    f_user_name: row.f_user_name,
    f_operat_type: '补卡',
    f_describe: '对用户' + row.f_user_name + '进行补卡操作',
    f_state: '未知',
    f_operator: Util.f.name,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname
  }
  return Vue.resetpost('rs/entity/t_fillcard', data, {resolveMsg: null, rejectMsg: '补卡存库失败'})
}

let saleWaterGen = function * (model, row) {
  let data = {
    f_real_prewater: model.f_prewater,
    f_preamount: model.f_preamount,
    f_user_id: row.f_user_id,
    f_userinfo_id: row.f_userinfo_id,
    record_userinfo: row.f_userinfo_id,
    f_operat_type: '用户发卡',
    f_describe: '对用户' + row.f_user_name + '进行发卡',
    f_state: '未知',
    f_operator: Util.f.name,
    f_delaypay: 0,
    f_charge_type: '用户发卡',
    chargeprice: model.chargeprice,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname,
    f_user_name: row.f_user_name,
    f_tablebase: model.f_curbalance,
    f_last_tablebase: model.f_last_tablebase,
    f_balance: (row.f_balance - 0),
    f_curbalance: (model.f_curbalance - 0),
    f_meter_type: row.f_meter_type,
    f_payment: model.f_payment[0],
    f_print_style: model.f_print[0],
    f_user_type: row.f_user_type,
    f_waterproperties: row.f_waterproperties,
    f_address: row.f_address,
    f_meter_brand: row.f_meter_brand,
    f_meter_style: row.f_meter_style,
    f_meternumber: row.f_meternumber,
    f_collection: model.f_preamount,
    f_coefficient: row.f_coefficient,
    f_meterbook_id: row.f_meterbook_id,
    f_meterbook_number: row.f_meterbook_number,
    f_charge_state: '有效',
    userinfo: {
      f_userinfo_id: row.f_userinfo_id,
      version: row.userinfo_version,
      f_balance: model.f_curbalance,
      userfiles: {
        f_user_id: model.f_user_id,
        f_whether_hairpin: '已发',
        f_meter_base: (row.f_meter_base - 0) + (model.f_prewater - 0),
        version: row.version
      }
    }
  }
  return Vue.resetpost('rs/logic/salecard', {data: data}, {resolveMsg: null, rejectMsg: '用户发卡存库失败'})
}

let cardChargeGen = function * (model, row) {
  let data = {
    f_real_prewater: model.f_prewater,
    f_preamount: model.f_preamount,
    record_userinfo: row.f_userinfo_id,
    f_userinfo_id: row.f_userinfo_id,
    f_user_id: row.f_user_id,
    f_card_id: row.f_card_id,
    f_operat_type: '卡表收费',
    f_describe: '对用户' + row.f_user_name + '进行卡表收费',
    f_state: '未知',
    f_operator: Util.f.name,
    f_delaypay: 0,
    f_charge_type: '卡表收费',
    chargeprice: model.chargeprice,
    f_filiale: Util.f.f_fengongsi,
    f_outlets: Util.f.f_parentname,
    f_user_name: row.f_user_name,
    f_tablebase: model.f_curbalance,
    f_last_tablebase: model.f_last_tablebase,
    f_balance: (row.f_balance - 0),
    f_curbalance: (model.f_curbalance - 0),
    f_meter_type: row.f_meter_type,
    f_payment: model.f_payment[0],
    f_print_style: model.f_print[0],
    f_user_type: row.f_user_type,
    f_waterproperties: row.f_waterproperties,
    f_address: row.f_address,
    f_meter_brand: row.f_meter_brand,
    f_meter_style: row.f_meter_style,
    f_meternumber: row.f_meternumber,
    f_collection: model.f_preamount,
    f_coefficient: row.f_coefficient,
    f_meterbook_id: row.f_meterbook_id,
    f_meterbook_number: row.f_meterbook_number,
    f_charge_state: '有效',
    userinfo: {
      f_userinfo_id: row.f_userinfo_id,
      version: row.userinfo_version,
      f_balance: model.f_curbalance,
      userfiles: {
        f_user_id: model.f_user_id,
        f_meter_base: (row.f_meter_base - 0) + (model.f_prewater - 0),
        f_times: row.f_times + 1,
        version: row.version
      }
    }
  }
  // if (row.cardInfo.Times === 1) {
  //   data.userinfo.userfiles.f_meterid = row.cardInfo.Yhh
  // }
  return Vue.resetpost('rs/logic/sellWater', data, {resolveMsg: null, rejectMsg: '卡表收费存库失败'})
}
let getParamGen = function * (cardid) {
  let data = {
    f_card_id: cardid
  }
  return co(Vue.resetpost('rs/logic/stairCard', {data: data}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'}))
}

let CardService = {
  install (Vue, options) {
    // 给vue增添对话框显示方法
    Vue.CardService = Vue.prototype.$CardService = CardService
  },
  // 开户发卡
  initCard (model, row) {
    let init = initCardGen(model, row)
    return co(init)
  },
  // 补卡存库
  reissueCard (model, row) {
    let reissue = reissueCardGen(model, row)
    return co(reissue)
  },
  // 补卡写卡
  replaceCard (model, row) {
    let replace = replaceCardGen(model, row)
    return co(replace)
  },
  // 售水存库
  salewater (model, row) {
    let salewater = saleWaterGen(model, row)
    return co(salewater)
  },
  // 售水写卡
  sellwater (model, row) {
    let sellwater = sellWaterGen(model, row)
    return co(sellwater)
  },
  // 卡表收费
  cardCharge (model, row) {
    let cardcharge = cardChargeGen(model, row)
    return co(cardcharge)
  }
}

export default CardService
